package br.com.bmb.monitorimoveis.persistencia.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import br.com.bmb.monitorimoveis.entidade.Anuncio;
import br.com.bmb.monitorimoveis.entidade.Bairro;
import br.com.bmb.monitorimoveis.persistencia.IAbstractDAO;



public abstract class AbstractDAO<ENTITY, IDTYPE extends Serializable> implements IAbstractDAO<ENTITY, IDTYPE> {
	
	@Autowired
	protected SessionFactory sf;
	
	public Session getSession() {
		Session session = sf.getCurrentSession();
		
		if (session == null)
			return sf.openSession();
		
		return session;
	}
	
	@SuppressWarnings("unchecked")
	public ENTITY inserir(ENTITY obj){		
		getSession().save(obj);
		return obj;
	}
	
	public void alterar(ENTITY obj){
		getSession().update(obj);
	}
	
	public void remover(ENTITY obj){
		getSession().delete(obj);
	}	
	
	
	
	@SuppressWarnings("unchecked")
	public ENTITY getById(IDTYPE id) {
		return (ENTITY) getSession().get(getObjectType(), id);
		
	}

	@SuppressWarnings("unchecked")
	public List<ENTITY> listAll() {
		Criteria criteria = getSession().createCriteria(getObjectType());		
		return criteria.list();
	}

	protected abstract Class<?> getObjectType();
				
	
}
